package zy.controller.stock;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import zy.controller.BaseController;
import zy.entity.PageData;
import zy.entity.stock.data.T_Stock_Data;
import zy.entity.stock.data.T_Stock_DataView;
import zy.entity.sys.improtinfo.T_Import_Info;
import zy.entity.sys.user.T_Sys_User;
import zy.form.PageForm;
import zy.form.ProductForm;
import zy.service.stock.data.DataService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.ExcelImportUtil;
import zy.util.StringUtil;

@Controller
@RequestMapping("stock/data")
public class DataController extends BaseController{
	
	@Resource
	private DataService dataService;
	
	/**
	 * 库存状况表
	 */
	@RequestMapping(value = "to_list", method = RequestMethod.GET)
	public String to_list() {
		return "stock/data/list";
	}
	
	/**
	 * 库存分仓表
	 */
	@RequestMapping(value = "to_list_bydepot", method = RequestMethod.GET)
	public String to_list_bydepot() {
		return "stock/data/list_bydepot";
	}
	/**
	 * 各店库存报表
	 */
	@RequestMapping(value = "to_list_byshop", method = RequestMethod.GET)
	public String to_list_byshop() {
		return "stock/data/list_byshop";
	}
	/**
	 * 店铺库存一览表
	 */
	@RequestMapping(value = "to_stock_shop", method = RequestMethod.GET)
	public String to_stock_shop() {
		return "stock/data/stock_shop";
	}
	/**
	 * 类别分级库存报表
	 */
	@RequestMapping(value = "to_type_level_stock/{tp_upcode}", method = RequestMethod.GET)
	public String to_type_level_stock(@PathVariable String tp_upcode,Model model) {
		model.addAttribute("tp_upcode", tp_upcode);
		return "stock/data/type_level_stock";
	}
	/**
	 * 库存分析报表
	 */
	@RequestMapping(value = "to_list_analysis/{type}", method = RequestMethod.GET)
	public String to_list_analysis(@PathVariable String type,Model model) {
		model.addAttribute("type", type);
		return "stock/data/list_analysis";
	}
	/**
	 * 单品跟踪
	 */
	@RequestMapping(value = "to_single_track", method = RequestMethod.GET)
	public String to_single_track() {
		return "stock/data/single_track";
	}
	
	@RequestMapping(value = "to_list_dialog_sale", method = RequestMethod.GET)
	public String to_list_dialog_sale() {
		return "stock/data/list_dialog_sale";
	}
	
	@RequestMapping(value = "to_import_stock", method = RequestMethod.GET)
	public String to_import_stock(HttpServletRequest request,Model model) {
		String depot_code = request.getParameter("depot_code");
		model.addAttribute("depot_code", depot_code);
		return "stock/data/import_stock";
	}
	
	@RequestMapping(value = "page", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object page(ProductForm productForm,
			@RequestParam(required = false) String type,
			@RequestParam(required = false) String depot_code,
			@RequestParam(required = false) String pd_no,
			@RequestParam(required = false) String pd_name,
			@RequestParam(required = false) Integer showColor,
			@RequestParam(required = false) Integer showSize,
			@RequestParam(required = false) Integer showBra,
			@RequestParam(required = false) Integer exactQuery,
			@RequestParam(required = false) String showZero,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.PAGESIZE, productForm.getRows());
        param.put(CommonUtil.PAGEINDEX, productForm.getPage());
        param.put(CommonUtil.SIDX, productForm.getSidx());
        param.put(CommonUtil.SORD, productForm.getSord());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("type", type);
        param.put("depot_code", depot_code);
        param.put("pd_no", StringUtil.decodeString(pd_no));
        param.put("pd_name", StringUtil.decodeString(pd_name));
        param.put("exactQuery", exactQuery);
        param.put("bd_code", productForm.getBd_code());
        param.put("tp_code", productForm.getTp_code());
        param.put("pd_season", productForm.getPd_season());
        param.put("pd_year", productForm.getPd_year());
        param.put("showColor", showColor);
        param.put("showSize", showSize);
        param.put("showBra", showBra);
        param.put("showZero", showZero);
		return ajaxSuccess(dataService.page(param));
	}
	
	@RequestMapping(value = "size_data", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object size_data(ProductForm productForm,
			@RequestParam(required = false) String type,
			@RequestParam(required = false) String depot_code,
			@RequestParam(required = false) String pd_no,
			@RequestParam(required = false) String pd_name,
			@RequestParam(required = false) Integer exactQuery,
			@RequestParam(required = false) String showZero,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.PAGESIZE, productForm.getRows());
        param.put(CommonUtil.PAGEINDEX, productForm.getPage());
        param.put(CommonUtil.SIDX, productForm.getSidx());
        param.put(CommonUtil.SORD, productForm.getSord());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("type", type);
        param.put("depot_code", depot_code);
        param.put("pd_no", StringUtil.decodeString(pd_no));
        param.put("pd_name", StringUtil.decodeString(pd_name));
        param.put("exactQuery", exactQuery);
        param.put("showZero", showZero);
        param.put("bd_code", productForm.getBd_code());
        param.put("tp_code", productForm.getTp_code());
        param.put("pd_season", productForm.getPd_season());
        param.put("pd_year", productForm.getPd_year());
		return ajaxSuccess(dataService.size_data(param));
	}
	
	@RequestMapping(value = "size_title", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object size_title(
			@RequestParam(required = false) String type,
			@RequestParam(required = false) String depot_code,
			@RequestParam(required = false) String pd_no,
			@RequestParam(required = false) String pd_name,
			@RequestParam(required = false) Integer exactQuery,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("type", type);
        param.put("depot_code", depot_code);
        param.put("pd_no", StringUtil.decodeString(pd_no));
        param.put("pd_name", StringUtil.decodeString(pd_name));
        param.put("exactQuery", exactQuery);
		return ajaxSuccess(dataService.size_title(param));
	}
	
	@RequestMapping(value = "page_bydepot", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object page_bydepot(PageForm pageForm,
			@RequestParam(required = false) String depot_code,
			@RequestParam(required = false) String pd_no,
			@RequestParam(required = false) String pd_name,
			@RequestParam(required = false) Integer exactQuery,
			@RequestParam(required = false) String bd_code,
			@RequestParam(required = false) String tp_code,
			@RequestParam(required = false) String pd_season,
			@RequestParam(required = false) String pd_year,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.PAGESIZE, pageForm.getRows());
        param.put(CommonUtil.PAGEINDEX, pageForm.getPage());
        param.put(CommonUtil.SIDX, pageForm.getSidx());
        param.put(CommonUtil.SORD, pageForm.getSord());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("depot_code", depot_code);
        param.put("pd_no", StringUtil.decodeString(pd_no));
        param.put("pd_name", StringUtil.decodeString(pd_name));
        param.put("exactQuery", exactQuery);
        param.put("bd_code", bd_code);
        param.put("tp_code", tp_code);
        param.put("pd_season", pd_season);
        param.put("pd_year", pd_year);
		return ajaxSuccess(dataService.page_bydepot(param));
	}
	
	@RequestMapping(value = "page_byshop", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object page_byshop(PageForm pageForm,
			@RequestParam(required = true) String type,
			@RequestParam(required = false) String shopCodes,
			@RequestParam(required = false) String pd_no,
			@RequestParam(required = false) Integer exactQuery,
			@RequestParam(required = false) String bd_code,
			@RequestParam(required = false) String tp_code,
			@RequestParam(required = false) String pd_season,
			@RequestParam(required = false) String pd_year,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.PAGESIZE, pageForm.getRows());
        param.put(CommonUtil.PAGEINDEX, pageForm.getPage());
        param.put(CommonUtil.SIDX, pageForm.getSidx());
        param.put(CommonUtil.SORD, pageForm.getSord());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("type", type);
        param.put("shopCodes", shopCodes);
        param.put("pd_no", StringUtil.decodeString(pd_no));
        param.put("exactQuery", exactQuery);
        param.put("bd_code", bd_code);
        param.put("tp_code", tp_code);
        param.put("pd_season", pd_season);
        param.put("pd_year", pd_year);
		return ajaxSuccess(dataService.page_byshop(param));
	}
	
	@RequestMapping(value = "list_analysis", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object list_analysis(PageForm pageForm,
			@RequestParam(required = true) String type,
			@RequestParam(required = false) String depot_code,
			@RequestParam(required = false) String pd_code,
			@RequestParam(required = false) String bd_code,
			@RequestParam(required = false) String tp_code,
			@RequestParam(required = false) String pd_season,
			@RequestParam(required = false) String pd_year,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.SIDX, pageForm.getSidx());
        param.put(CommonUtil.SORD, pageForm.getSord());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("type", type);
        param.put("depot_code", depot_code);
        param.put("bd_code", bd_code);
        param.put("tp_code", tp_code);
        param.put("pd_code", pd_code);
        param.put("pd_season", pd_season);
        param.put("pd_year", pd_year);
		return ajaxSuccess(dataService.list_analysis(param));
	}
	
	@RequestMapping(value = "stock_shop", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object stock_shop(PageForm pageForm,
			@RequestParam(required = false) String shopCodes,
			@RequestParam(required = false) String pd_code,
			@RequestParam(required = false) String bd_code,
			@RequestParam(required = false) String tp_code,
			@RequestParam(required = false) String pd_season,
			@RequestParam(required = false) String pd_year,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.SIDX, pageForm.getSidx());
        param.put(CommonUtil.SORD, pageForm.getSord());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("bd_code", bd_code);
        param.put("tp_code", tp_code);
        param.put("pd_code", pd_code);
        param.put("pd_season", pd_season);
        param.put("pd_year", pd_year);
        param.put("shopCodes", shopCodes);
		return ajaxSuccess(dataService.stock_shop(param));
	}
	
	@RequestMapping(value = "type_level_stock", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object type_level_stock(@RequestParam(required = true) String tp_upcode,
			@RequestParam(required = false) String shopCodes,
			@RequestParam(required = false) String pd_code,
			@RequestParam(required = false) String bd_code,
			@RequestParam(required = false) String pd_season,
			@RequestParam(required = false) String pd_year,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put("bd_code", bd_code);
        param.put("pd_code", pd_code);
        param.put("pd_season", pd_season);
        param.put("pd_year", pd_year);
        param.put("shopCodes", shopCodes);
        param.put("tp_upcode", tp_upcode);
		return ajaxSuccess(dataService.type_level_stock(param));
	}
	
	@RequestMapping(value = "single_track", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object single_track(ProductForm productForm,@RequestParam(required = false) String dp_code,
			HttpSession session) {
		T_Sys_User user = getUser(session);
        Map<String,Object> params = new HashMap<String, Object>();
        params.put(CommonUtil.COMPANYID, getCompanyid(session));
        params.put(CommonUtil.PAGESIZE, productForm.getRows());
        params.put(CommonUtil.PAGEINDEX, productForm.getPage());
        params.put(CommonUtil.SIDX, productForm.getSidx());
        params.put(CommonUtil.SORD, productForm.getSord());
        params.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        params.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        params.put("dp_code", dp_code);
        params.put("begindate", productForm.getBegindate());
        params.put("enddate", productForm.getEnddate());
        params.put("pd_code", productForm.getPd_code());
        params.put("cr_code", productForm.getCr_code());
        params.put("sz_code", productForm.getSz_code());
		return ajaxSuccess(dataService.single_track(params));
	}
	
	/**
	 * 促销方案查询商品库存
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "data_list_sale", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object data_list_sale(HttpServletRequest request,HttpSession session) {
		String page = request.getParameter("page"); // 页码
        String rows = request.getParameter("rows"); // 每页条数
        String sidx = request.getParameter("sidx");
        String sord = request.getParameter("sord");
        String searchContent = request.getParameter("searchContent");
        String isGift = request.getParameter("isGift");
        String pd_no = request.getParameter("pd_no");
        String pd_name = request.getParameter("pd_name");
        String pd_spell = request.getParameter("pd_spell");
        String pd_year = request.getParameter("pd_year");
        String pd_season = request.getParameter("pd_season");
        String pd_tp_code = request.getParameter("pd_tp_code");
        String pd_bd_code = request.getParameter("pd_bd_code");
        
        int pageIndex = 1;
        int pageSize = super.pagesize;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(page)) {
        	pageIndex = Integer.parseInt(page);
        	pageIndex = pageIndex == 0 ? 1 : pageIndex;
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(rows)) {
        	pageSize = Integer.parseInt(rows);
        }
        T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, user.getCompanyid());
        param.put(CommonUtil.SHOP_TYPE, user.getShoptype());
        param.put(CommonUtil.SHOP_CODE, user.getUs_shop_code());
        param.put(CommonUtil.PAGESIZE, pageSize);
        param.put(CommonUtil.PAGEINDEX, pageIndex);
        param.put(CommonUtil.SIDX, sidx);
        param.put(CommonUtil.SORD, sord);
        param.put("searchContent", StringUtil.decodeString(searchContent));
        param.put("isGift", isGift);
        param.put("pd_no", pd_no);
        param.put("pd_name", StringUtil.decodeString(pd_name));
        param.put("pd_spell", StringUtil.decodeString(pd_spell));
        param.put("pd_year", pd_year);
        param.put("pd_season", StringUtil.decodeString(pd_season));
        param.put("pd_tp_code", pd_tp_code);
        param.put("pd_bd_code", pd_bd_code);
		PageData<T_Stock_DataView> pageData = dataService.data_list_sale(param);
		return ajaxSuccess(pageData, "查询成功, 共" + pageData.getList().size() + "条数据");
	}
	
	@RequestMapping(value = "save_import_stock", method = RequestMethod.POST,produces = "text/html; charset=utf-8")
	@ResponseBody
	public Object save_import_stock(MultipartFile excel,HttpServletRequest request,HttpSession session)throws IOException {
		if (excel == null || excel.getSize() <= 0) {
			return ajaxFail("请选择需要导入的文件！"); 
		}
		Map<String,Object> param = new HashMap<String, Object>();
		Workbook sourceWorkBook = null;
		Workbook wb_error = null;
		WritableWorkbook wb = null;
		
		try {
			String depot_code = request.getParameter("depot_code");
			T_Sys_User user = getUser(session);
			param.put("companyid", user.getCompanyid());
			param.put("us_id", user.getUs_id());
			//根据商家编号、用户编号及当前时间生成文件名
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = "stock_" + user.getCompanyid() + (user.getUs_id() + format.format(new Date())) + ".xls";
			
			// 复制客户端文件到服务器临时文件夹进行处理,处理完以后删除
			String temp_uploaddir = CommonUtil.CHECK_BASE + CommonUtil.EXCEL_PATH;
			String toFilePath = temp_uploaddir + File.separator + fileName;
			File savefile = new File(toFilePath);
			if (!savefile.getParentFile().exists()) {
				savefile.getParentFile().mkdirs();
			}
			excel.transferTo(savefile);
			
			// Excel 模板文件路径，把模板文件复制，然后作为错误文件进行数据追加
			String relPath = session.getServletContext().getRealPath("resources");
			String excel_member_template = relPath + File.separator + "excel" + File.separator + CommonUtil.STOCKLEADING;
			
			// 错误文件名称
			String errFileName = "fail" + fileName;
			String errorFilePath = temp_uploaddir + File.separator + errFileName;
			File excel_template = new File(excel_member_template);// 原有Excel 模板文件
			File errorFile = new File(errorFilePath);// 生成的错误文件路径
			// 把模板文件复制给错误文件
			FileUtils.copyFile(excel_template, errorFile);
			
			sourceWorkBook = Workbook.getWorkbook(savefile);// 要导入的Excel
			wb_error = Workbook.getWorkbook(errorFile);
			wb = Workbook.createWorkbook(errorFile, wb_error);
			Map<String, Object> result = dataService.parseSavingStockExcel(sourceWorkBook, wb, user,depot_code);
			wb.write();
			
			ExcelImportUtil.deleteFile(savefile);
			int success = (Integer)(result.get("success"));// 导入成功条数
			int fail = (Integer)(result.get("fail"));// 导入失败条数
			param.put("updateStockList", (List<T_Stock_Data>)result.get("updateStockList"));//验证成功的库存（修改库存数量）
			param.put("inserStockList", (List<T_Stock_Data>)result.get("inserStockList"));//验证成功的库存（新增）
			
			T_Import_Info t_Import_Info = new T_Import_Info();
			t_Import_Info.setIi_success(success);
			t_Import_Info.setIi_fail(fail);
			t_Import_Info.setIi_total(success+fail);
			t_Import_Info.setIi_filename(excel.getOriginalFilename());
			t_Import_Info.setIi_error_filename(errFileName);
			t_Import_Info.setIi_us_id(user.getUs_id());
			t_Import_Info.setIi_sysdate(DateUtil.getCurrentTime());
			t_Import_Info.setIi_type(CommonUtil.IMPROT_STOCKTYPE);
			t_Import_Info.setCompanyid(user.getCompanyid());
			param.put("t_Import_Info", t_Import_Info);
			param.put("ii_type", CommonUtil.IMPROT_STOCKTYPE);
			
			dataService.save_import_stock(param);
		}  catch (Exception e){
			e.printStackTrace();
			return ajaxFail("导入失败，请联系管理员！");
		} finally {
			if (sourceWorkBook != null)
				sourceWorkBook.close();
			if (wb_error != null)
				wb_error.close();
			try {
				if (wb != null)
					wb.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return ajaxSuccess();
	}
}
